//
//  DDBossTagViewController.m
//  DingDongZP
//
//  Created by Ray on 16/4/22.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDBossTagViewController.h"
#import "DDBossTagCell.h"
#import "DDTagHeadView.h"
#import "DDBossInfoService.h"

@interface DDBossTagViewController ()
<UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout>
@property (nonnull, strong) UICollectionView *collectionView;

@property (nonatomic, strong) DDBossInfoService *infoService;
@property (nonatomic, strong) NSArray *allTags;

@end

@implementation DDBossTagViewController

- (DDBossInfoService *)infoService
{
    if (!_infoService) {
        _infoService = [[DDBossInfoService alloc] init];
    }
    return _infoService;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"团队亮点";
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 10;
    layout.sectionInset = UIEdgeInsetsMake(0, 20, 0, 20);
    layout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 35);
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.backgroundColor = COLOR_BACKGROUND;
    self.collectionView.allowsMultipleSelection = YES;
    [self.view addSubview:_collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.collectionView registerNib:[UINib nibWithNibName:@"DDBossTagCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"DDTagHeadView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];
    
    /// 大小按屏幕大小来计算
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - 40 - 10*2) / 3.0, 40);
    
    /// 加载数据
    [self loadTags];
    
    self.navigationItem.rightBarButtonItem = self.confirmItem;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - functions
- (BOOL)indexPathLast:(NSIndexPath *)indexPath
{
    NSInteger count = [self collectionView:_collectionView numberOfItemsInSection:indexPath.section];
    return indexPath.row == (count - 1);
}

- (void)loadTags
{
    WEAKSELF
    [self showLoading];
    [self.infoService queryHighlights:^(NSArray *highlights) {
        [weakSelf hideLoading];
        [weakSelf updateWithTags:highlights];
        
    }];
}

- (void)updateWithTags:(NSArray *)allTags
{
    self.allTags = allTags;
    [self.collectionView reloadData];
    
    /// 根据传入的选中亮点，设置选中item
    for (DDTeamHighlightTag *ntag in allTags) {
        for (NSDictionary *mtag in self.selectedTags) {
            if ([mtag[@"tagid"] isEqualToString:ntag.tag_id]) {
                NSInteger idx = [allTags indexOfObject:ntag];
                NSIndexPath *path = [NSIndexPath indexPathForRow:idx inSection:0];
                [self.collectionView selectItemAtIndexPath:path
                                                  animated:YES
                                            scrollPosition:UICollectionViewScrollPositionNone];
                break;
            }
        }
    }
}

#pragma mark - actions
- (void)actionConfirm:(UIButton *)btn
{
    NSArray *selectedPath = [self.collectionView indexPathsForSelectedItems];
    NSMutableDictionary *infos = [NSMutableDictionary new];
    infos[@"tagsNum"] = @(selectedPath.count);
    NSMutableArray *tagIds = [NSMutableArray new];
    for (NSIndexPath *path in selectedPath) {
        DDTeamHighlightTag *tag = [self.allTags objectAtIndex:path.row];
        [tagIds addObject:tag.tag_id];
    }
    infos[@"tagsIDs"] = tagIds;
    
    NSString *taginfoString = [infos jsonStringEncoded];
    if (self.didSelectTags) {
        self.didSelectTags(taginfoString);
    }
    [self.navigationController popViewControllerAnimated:YES];
}
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self indexPathLast:indexPath]) {
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        
        return YES;
        
    } else {
        NSArray *selectedPath = [self.collectionView indexPathsForSelectedItems];
        if (selectedPath.count > 7) {
            [self showToastOnCenter:@"最多选择8个标签"];
            return NO;
        }
    }
    return YES;
}

#pragma mark - delegates

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _allTags.count + 1;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    DDBossTagCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (indexPath.row < _allTags.count) {
        DDTeamHighlightTag *tag = _allTags[indexPath.row];
        cell.nameLab.text = tag.tag_text;
    }
    else {
        cell.nameLab.text = @"+";
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self indexPathLast:indexPath]) {
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        
        /// 添加新的标签
        
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader) {
        DDTagHeadView *head = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"head" forIndexPath:indexPath];
        return head;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *content = nil;
    if (indexPath.row < _allTags.count) {
        DDTeamHighlightTag *tag = _allTags[indexPath.row];
        content = tag.tag_text;
    }
    else {
        content = @"+";
    }
    CGRect bound = [content boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 40) options:kNilOptions attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15.0]} context:nil];
    return CGSizeMake(bound.size.width+16, 40);
    return CGSizeZero;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
